package TwoAgain;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class CommodityServiceImpl implements ICommodityService{
    private static List<Commodity> list = new ArrayList<>();
    static {
        Reader r = null;
        BufferedReader br = null;

        try {
            r = new FileReader("Housework0916/src/TwoAgain/commodity.txt");
            br = new BufferedReader(r);
            String str = null;
            while ((str=br.readLine())!=null){
                String[] value = str.split("\\s+");
                Commodity c = new Commodity(Integer.parseInt(value[0]),value[1],Integer.parseInt(value[2]));
                list.add(c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                br.close();
                r.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public List<Commodity> showAll() {
        return list;
    }

    @Override
    public Commodity search(int code) {
        int index = list.indexOf(new Commodity(code));
        if (index!=-1){
            return list.get(index);
        }
        return null;
    }
}
